// 测试WebSocket客户端连接
const WebSocket = require('ws');

console.log('========================================');
console.log('测试WebSocket客户端连接');
console.log('========================================\n');

const ws = new WebSocket('ws://localhost:7663');

ws.on('open', () => {
  console.log('✓ WebSocket连接成功\n');
  
  // 发送连接消息
  console.log('发送连接消息...');
  ws.send(JSON.stringify({
    type: 'connect',
    clientId: 'test-client-' + Date.now()
  }));
  
  // 等待2秒后发送控制指令
  setTimeout(() => {
    console.log('\n发送"下一页"控制指令...');
    ws.send(JSON.stringify({
      type: 'control',
      action: 'next',
      timestamp: Date.now()
    }));
    
    setTimeout(() => {
      console.log('发送"上一页"控制指令...');
      ws.send(JSON.stringify({
        type: 'control',
        action: 'previous',
        timestamp: Date.now()
      }));
      
      setTimeout(() => {
        console.log('\n✓ 测试完成，关闭连接');
        ws.close();
      }, 2000);
    }, 2000);
  }, 2000);
});

ws.on('message', (data) => {
  try {
    const message = JSON.parse(data);
    console.log('收到服务器消息:', message.type);
    
    if (message.type === 'connected') {
      console.log('  ✓ 服务器确认连接');
      console.log(`  当前幻灯片: ${message.currentSlide || '未知'}`);
    } else if (message.type === 'slideUpdate') {
      console.log('  ✓ 收到幻灯片更新');
      console.log(`  页码: ${message.slideIndex}`);
      console.log(`  图像大小: ${(message.imageData.length / 1024).toFixed(2)} KB`);
    } else if (message.type === 'error') {
      console.log('  ✗ 错误:', message.message);
    }
  } catch (error) {
    console.log('解析消息失败:', error.message);
  }
});

ws.on('error', (error) => {
  console.log('✗ WebSocket错误:', error.message);
  process.exit(1);
});

ws.on('close', () => {
  console.log('\nWebSocket连接已关闭');
  process.exit(0);
});

// 超时保护
setTimeout(() => {
  console.log('\n测试超时');
  ws.close();
  process.exit(1);
}, 15000);
